package com.landian.commons.base.utils;

import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * PasswordUtils
 *
 * @author caojl
 * @create 2017/12/13
 **/
public class PasswordUtils {

    /**利用MD5进行加密
     * @param str  待加密的字符串
     * @return  加密后的字符串
     * @throws NoSuchAlgorithmException  没有这种产生消息摘要的算法
     * @throws UnsupportedEncodingException
     */
    public static String encoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5=MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        //加密后的字符串
        String newStr=base64en.encode(md5.digest(str.getBytes("utf-8")));
        return newStr;
    }

    /**判断用户密码是否正确
     * @param newPassword  用户输入的密码
     * @param oldPassword  数据库中存储的密码－－用户密码的摘要
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static boolean checkPassword(String newPassword, String oldPassword){
        try {
            if(encoderByMd5(newPassword).equals(oldPassword)){
                return true;
            }else{
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    public static void main(String[] args) {
        try {
            String encoderByMd5 = PasswordUtils.encoderByMd5("");
            boolean checkPassword = checkPassword("", encoderByMd5);
            System.out.println(checkPassword);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
